import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {
    private static Set<ClientHandler> clientHandlers = new HashSet<>();
    private static int port = 12345;

    public static void main(String[] args) {
        System.out.println("服务器在端口上启动 " + port + ". 等待客户...");

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("新客户端已连接");

                ClientHandler clientHandler = new ClientHandler(clientSocket);
                clientHandlers.add(clientHandler);

                Thread thread = new Thread(clientHandler);
                thread.start();
            }
        } catch (IOException e) {
            System.out.println("服务器异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 广播消息给所有客户端（除了发送者）
    public static void broadcast(String message, ClientHandler sender) {
        // 确保消息不为空且有内容
        if (message == null || message.trim().isEmpty()) {
            return;
        }

        // 遍历所有客户端并发送消息
        for (ClientHandler client : clientHandlers) {
            // 不向发送者自己发送消息（除非是系统通知）
            if (sender == null || !client.equals(sender)) {
                client.sendMessage(message);
            }
        }

        // 打印到服务器控制台，用于调试
        System.out.println("Broadcast: " + message);
    }

    // 从客户端列表中移除客户端
    public static void removeClient(ClientHandler clientHandler) {
        clientHandlers.remove(clientHandler);
        updateUserList();
    }

    // 更新所有客户端的用户列表
    public static void updateUserList() {
        StringBuilder userList = new StringBuilder("USER_LIST:");

        for (ClientHandler client : clientHandlers) {
            if (userList.length() > "USER_LIST:".length()) {
                userList.append(",");
            }
            userList.append(client.getUsername());
        }

        // 发送用户列表给所有客户端
        for (ClientHandler client : clientHandlers) {
            client.sendMessage(userList.toString());
        }
    }
}
